<?php
//patikrinimui ar puslapaia atveriami taip kaip reikia
if (basename($_SERVER['PHP_SELF']) == 'funkcijos.php') { ban("Tiesioginis kreipimasis į failą"); }
define("OK",TRUE);

$inyecc='/SERVER|http|SELECT|UNION|UPDATE|INSERT/i';

if (preg_match($inyecc, $_SERVER['QUERY_STRING'])) {
	$ip = getip();
	$forwarded = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
	$remoteaddress = $HTTP_SERVER_VARS["REMOTE_ADDR"];
	ban('Bloga GET užklausa');
}

/**
 * Uždrausti IP ant serverio
 *
 * @param string $kodel
 */
function ban($kodel='XSS') {
	global $_SERVER,$ip,$forwarded,$remoteaddress;
	$atidaryti = fopen(".htaccess", "a+");
	@fwrite($atidaryti, "\n#".date('Y m d H:M:S')." - FROM:".$_SERVER["HTTP_REFERER"]." - REQ:".$_SERVER['REQUEST_METHOD']." - FILE:".basename($_SERVER['SCRIPT_FILENAME'])." - QUERY:".$_SERVER['QUERY_STRING']."\ndeny from ".getip()."\n");
	@fclose($atidaryti);
	@chmod(".htaccess", 0777);

	$forwarded = (isset($forwarded)?$forwarded:'N/A');
	$remoteaddress = (isset($remoteaddress)?$remoteaddress:'N/A');
	$ip = (isset($ip)?$ip:getip());
	$referer = (isset($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:'N/A');

	$message = <<<HTML
		FROM:{$referer}
		REQ:{$_SERVER['REQUEST_METHOD']}
		FILE:{$_SERVER['SCRIPT_FILENAME']}
		QUERY:{$_SERVER['QUERY_STRING']}
		IP:{$ip} - Forwarded = {$forwarded} - Remoteaddress = {$remoteaddress}
HTML;

	mail("projektas@gmail.com", date('Y-m-d')." - mrcbug.com", $message,"From: host@{$_SERVER['SERVER_NAME']}");
	die("<center><h1>Bomžams NE!</h1><font color='red'><b>".$kodel." - DRAUDŽIAMA<blink>!</blink></b></font><hr/>Susisiekite su administracija: info[eta]mrcbug[taskas]com</center>");
}

/// ASPAUGA - NETRINK - Pagal php-fusion

/*foreach ($_GET as $check_url) {
if ((eregi("<[^>]*script*\"?[^>]*>", $check_url)) || (eregi("<[^>]*object*\"?[^>]*>", $check_url)) ||
(eregi("<[^>]*iframe*\"?[^>]*>", $check_url)) || (eregi("<[^>]*applet*\"?[^>]*>", $check_url)) ||
(eregi("<[^>]*meta*\"?[^>]*>", $check_url)) || (eregi("<[^>]*style*\"?[^>]*>", $check_url)) ||
(eregi("<[^>]*form*\"?[^>]*>", $check_url)) || (eregi("\([^>]*\"?[^)]*\)", $check_url)) ||
(eregi("\"", $check_url))) { ban('GET patikra'); }
}
unset($check_url);*/

// Sanitise $_SERVER globals
$_SERVER['PHP_SELF'] = cleanurl($_SERVER['PHP_SELF']);
$_SERVER['QUERY_STRING'] = isset($_SERVER['QUERY_STRING']) ? cleanurl($_SERVER['QUERY_STRING']) : "";
$_SERVER['REQUEST_URI'] = isset($_SERVER['REQUEST_URI']) ? cleanurl($_SERVER['REQUEST_URI']) : "";
$PHP_SELF = cleanurl($_SERVER['PHP_SELF']);
// Common definitions

/**
 * Adreso apsauga pagal php-fusion
 *
 * @param unknown_type $url
 * @return unknown
 */
function cleanurl($url) {
	$bad_entities = array("&", '"', "'", "<", ">", "(", ")",'\\');
	$safe_entities = array("&amp;", "", "", "", "", "", "", "");
	$url = str_replace($bad_entities, $safe_entities, $url);
	return $url;
}

/// ASPAUGA - END

//sutvarkom nuorodas
if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) { $_GET = cleanurl(url_arr($_SERVER['QUERY_STRING'])); $url = cleanurl(url_arr($_SERVER['QUERY_STRING'])); }
else { $_GET = cleanurl(array()); $url = cleanurl(array()); }



// bandom skaiciuoti mysql uzklausas TESTAS
/**
 * MySQL užklausoms
 *
 * @param sql string $query
 * @return resource
 */
function mysql_query1($query) {
	global $mysql_num;
	if (defined("LEVEL") && LEVEL > 20) { 
		$mysql_num++;
	}
	return mysql_query($query);
}

//Nuskaitom info is URL
function http_get( $url ) {
	$request = fopen( $url, "rb" );
	$result = "";
	while( !feof( $request ) ) {
		$result .= fread( $request, 8192 );
	}
	fclose( $request );
	return $result;
}

//imam info is XML
function get_tag_contents( $xml, $tag ) {
	$result = "";
	$s_tag = "<$tag>";
	$s_offs = strpos( $xml, $s_tag );

	// If we found a starting offset, then look for the end-tag.
	if( $s_offs ) {
		$e_tag = "</$tag>";
		$e_offs = strpos( $xml, $e_tag, $s_offs );

		// If we have both tags, then dig out the contents.
		if( $e_offs ) {
			$result = substr(
			$xml,
			$s_offs + strlen( $s_tag ),
			$e_offs - $s_offs - strlen( $e_tag ) + 1 );
		}
	}

	return $result;
}

//Suskaiciuojam kiek nurodytoje lenteleje yra yrasu
function kiek($table,$where='',$as="viso") {
	$viso = mysql_fetch_assoc(mysql_query1("SELECT count(id) AS $as FROM `".LENTELES_PRIESAGA.$table."` ".$where));
	if (isset($viso[$as])) return $viso[$as];
	else return false;
}

//puslapiavimui
/**
 * Puslapiavimui generuoti
 *
 * @param puslapis $start
 * @param limit $count
 * @param viso $total
 * @param po kiek $range
 * @return unknown
 */
function puslapiai($start,$count,$total,$range=0){
	$res="";
	$pg_cnt=ceil($total / $count);
	if ($pg_cnt > 1) {
		$idx_back = $start - $count;
		$idx_next = $start + $count;
		$cur_page=ceil(($start + 1) / $count);
		$res.="";
		$res.="<center>\n";
		if ($idx_back >= 0) {
			if ($cur_page > ($range + 1)) $res.="<a href='".url("p,0")."'>[<u>««</u>]</a>\n";
			$res.="<a href='".url("p,$idx_back")."'>[<u>«</u>]</a>\n";
		}
		$idx_fst=max($cur_page - $range, 1);
		$idx_lst=min($cur_page + $range, $pg_cnt);
		if ($range==0) {
			$idx_fst = 1;
			$idx_lst=$pg_cnt;
		}
		for($i=$idx_fst;$i<=$idx_lst;$i++) {
			$offset_page=($i - 1) * $count;
			if ($i==$cur_page) {
				$res.="<font color='red'>[<u><b>$i</b></u>]</font>\n";
			} else {
				$res.="<a href='".url("p,$offset_page")."'>[<u>$i</u>]</a>\n";
			}
		}
		if ($idx_next < $total) {
			$res.="<a href='".url("p,$idx_next")."'>[<u>»</u>]</a>\n";
			if ($cur_page < ($pg_cnt - $range)) {
				$res.="<a href='".url("p,".($pg_cnt-1)*$count."")."'>[<u>»»</u>]</a>\n";
			}
		}
		$res.="</center>\n";
	}
	return $res;
}

/**
 * Tikrina ar kintamasis teigiamas skaicius
 *
 * @param num $value
 * @return 1 or NULL
 */
function isNum($value) {
	if (!is_array($value)) { return (preg_match("/^[0-9]+$/", $value)); }
	else { return false; }
}

/**
 * Gražina lankytojo IP
 *
 * @return string
 */
function getip() {
	if(getenv('HTTP_X_FORWARDED_FOR')){
		$ip2 = ''; $ip3 = '';
		$ip = $_SERVER['REMOTE_ADDR'];
		if(preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", getenv('HTTP_X_FORWARDED_FOR'), $ip3)){
			$ip2 = array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.16\..*/', '/^10..*/', '/^224..*/', '/^240..*/');
			$ip = preg_replace($ip2, $ip, $ip3[1]);
		}
	}else{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	if($ip == ""){ $ip = "x.x.x.x"; }
	return $ip;
}
function random_name($i=10) {
	$chars = "abcdefghijkmnopqrstuvwxyz023456789";
	srand((double)microtime()*1000000);
	$name = '' ;
	while ($i >= 0) {
		$num = rand() % 33;
		$tmp = substr($chars, $num, 1);
		$name = $name . $tmp;
		$i--;
	}
	return $name;
}

/**
 * Sutvarko SQL užklausą
 *
 * @param string $sql
 * @return escaped string
 */
function escape($sql) {
	// Stripslashes
	if (get_magic_quotes_gpc()) {
		$sql = stripslashes($sql);
	}
	//Jei ne skaičius
	if (!isnum($sql) || $sql[0] == '0') {
		if (!isnum($sql)) {
			$sql = "'" . mysql_real_escape_string($sql) . "'";
		}
	}
	return $sql;
}

/**
 * Sutvarkom stringą saugiam atvaizdavimui
 * sito reikia jei nori grainti i inputa informacija.
 * daznai tai buna su visokiais \\\'? ir pan
 *
 * @param string $s
 * @return formated string
 */
function input($s) {
	$s = htmlspecialchars($s, ENT_QUOTES);
	return $s;
}

/////////////////////////////////////////////////////////
//////// URL APDOROJIMUI
////////////////////////////////////////////////////////

/**
 * Iš QUERY_STRING padarom masyvą
 *
 * @param QUERY_STRING $params
 * @return array
 */
function url_arr($params) {
	if (!isset($params)) { $params = $_SERVER['QUERY_STRING']; }
	$params = explode(";", $params); $str2 = '';
	if (isset($params) && is_array($params) && count($params) > 0) {
		foreach ($params as $key => $value) {
			$str1 = explode(",",$value);
			if (isset($str1[1])) $str2[$str1[0]] = $str1[1];
		}
	}
	return $str2;
}

/**
 * Iš masyvo padarom į QUERY_STRING
 * dekui: "sliekas_kanibalas" uz patobulinima
 *
 * @param array $params
 * @param string $str
 * @return string
 */
function arr_url($params,$str='') {
	$strs = array();
	foreach ($params as $key => $value) {
		$strs[] = $key . ',' . rawurlencode($value);
	}
	$str .= implode( ";", $strs );
	return ($str);
}

/**
 * Papildo nuorodą naujais kintamaisiais
 * Esant reikalui atnaujina esamus
 *
 * @param string $str
 * @param string $link
 * @return formated string
 */
function url($str,$link=''){
	if (!empty($_SERVER['QUERY_STRING'])) {
		$url = url_arr($_SERVER['QUERY_STRING']);
	}
	else { $url = array(); }
	if (!is_array($str)) {
		$str = url_arr($str);
	}
	return $link."?".arr_url(array_merge($url,$str));
}
/////////////////////////////////////////////////////////////
///////// URL PABAIGA
/////////////////////////////////////////////////////////////

//peradresavimo budai
/**
 * Peradresavimas
 *
 * @param address $location
 * @param header/meta/script $type
 */
function redirect($location, $type="header") {
	if ($type == "header") {
		header("Location: ".$location);
	}
	if ($type == "meta") {
		echo "<meta http-equiv='Refresh' content='1;url=$location'>";
	}
	else {
		echo "<script type='text/javascript'>document.location.href='".$location."'</script>\n";
	}
}

/**
 * Gražina amžių, nurodžius datą
 *
 * @param string $data
 * @return int
 */
function amzius($data) {
	if (!isset($data) || $data == '' || $data == '0000-00-00') { return "- "; }
	else {
		$data = explode ("-", $data);
		$amzius = time() - mktime(0,0,0,$data['1'],$data['2'],$data['0']);
		$amzius = date("Y",$amzius) - 1970;
		return $amzius;
	}
}

function descript($text,$striptags=true) {
	// Convert problematic ascii characters to their true values
	$search = array("40","41","58","65","66","67","68","69","70",
	"71","72","73","74","75","76","77","78","79","80","81",
	"82","83","84","85","86","87","88","89","90","97","98",
	"99","100","101","102","103","104","105","106","107",
	"108","109","110","111","112","113","114","115","116",
	"117","118","119","120","121","122","239"
	);
	$replace = array("(",")",":","a","b","c","d","e","f","g","h",
	"i","j","k","l","m","n","o","p","q","r","s","t","u",
	"v","w","x","y","z","a","b","c","d","e","f","g","h",
	"i","j","k","l","m","n","o","p","q","r","s","t","u",
	"v","w","x","y","z",""
	);
	$entities = count($search);
	for ($i=0;$i < $entities;$i++) $text = preg_replace("#(&\#)(0*".$search[$i]."+);*#si", $replace[$i], $text);
	$text = str_replace(chr(32).chr(32), "&nbsp;", $text);
	$text = str_replace(chr(9), "&nbsp; &nbsp; &nbsp; &nbsp;", $text);
	// the following is based on code from bitflux (http://blog.bitflux.ch/wiki/)
	// Kill hexadecimal characters completely
	$text = preg_replace('#(&\#x)([0-9A-F]+);*#si', "", $text);
	// remove any attribute starting with "on" or xmlns
	$text = preg_replace('#(<[^>]+[\\"\'\s])(onmouseover|onmousedown|onmouseup|onmouseout|onmousemove|onclick|ondblclick|onload|xmlns)[^>]*>#iU', ">", $text);
	// remove javascript: and vbscript: protocol
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)script:#iU', '$1=$2nojscript...', $text);
	$text = preg_replace('#([a-z]*)=([\`\'\"]*)javascript:#iU', '$1=$2nojavascript...', $text);
	$text = preg_replace('#([a-z]*)=([\'\"]*)vbscript:#iU', '$1=$2novbscript...', $text);
	//<span style="width: expression(alert('Ping!'));"></span> (only affects ie...)
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU', "$1>", $text);
	$text = preg_replace('#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU', "$1>", $text);
	if ($striptags) {
		do {
			$thistext = $text;
			$text = preg_replace('#</*(applet|meta|xml|blink|link|style|script|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $text);
		} while ($thistext != $text);
	}
	return $text;
}
function isImage1($matches) {
	//$img = $matches[1].str_replace(array("?","&","="),"",$matches[3]).$matches[4];
	$img = $matches[1].$matches[3].$matches[4];
	if (@getimagesize($img)) {
		$res = "<img src='".$img."' style='border:0px;'>";
	}
	else {
		$res = "[img]".$img."[/img]";
	}
	return $res;
}

//Sulauzom zodi jei perilgas - lauzo net ir jei zodis turi tarpus
function wrap1($text,$chars=25) {
	$text = wordwrap($text, $chars, "<br />\n", 1);
	return $text;
}
//Sulauzo zodi tik jei jis yra be tarpu ir perilgas
function wrap($string,$width,$break="\n") {
	$string = preg_replace('/([^\s]{'.$width.'})/i',"$1$break",$string);
	return $string;
}

//tikrinam ar kintamasis sveikas skaicius ar normalus zodis
function tikrinam ($txt) {
	return (preg_match("/^[0-9a-zA-Z]+$/",$txt));
}

//bano galiojimo laikas. Rodo data iki kada +30 dienu
//echo "Galioja iki: ".galioja('12', '19', '2007');
//grazina: Galioja iki: 2008-01-17
function galioja($menuo,$diena,$metai,$kiek_galioja=30) {
	$nuo = (int)(mktime(0,0,0,$menuo,$diena,$metai)- time(void)/86400);
	$liko = $nuo + ($kiek_galioja * 24 * 60 * 60);
	return date('Y-m-d',$liko);
}

function liko($diena, $menuo, $metai){
	$until = mktime(0,0,0,$menuo,$diena,$metai);
	$now = time();
	$difference = $until - $now;
	$days = floor($difference/86400);
	$difference = $difference - ($days*86400);
	$hours = floor($difference/3600);
	$difference = $difference - ($hours*3600);
	$minutes = floor($difference/60);
	$difference = $difference - ($minutes*60);
	$seconds = $difference;
	return (int)$days + 1;
}

//sutvarko url iki linko
function linkas($str) {
	$str = strtolower(strip_tags($str));
	//return preg_replace_callback("#([\n ])([a-z]+?)://([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+]+)#si", "linkai", $str);
	return preg_replace("`((http)+(s)?:(//)|(www\.))((\w|\.|\-|_)+)(/)?(\S+)?`i", "<a href=\"http://\\5\\6\" title=\"\\0\" target=\"_blank\" class=\"link\" >\\5\\6</a>", $str);
}

// apvalinti:
// suapvalina nurodyta skaičiu
// (išesmės veikia kaip ceil() tik leidžia nurodyti dešimtainę)
function apvalinti($sk, $kiek) {
	if ($kiek < 0) { $kiek = 0; }
	$mult = pow(10, $kiek);
	return ceil($sk * $mult) / $mult;
}

function naujas($data,$nick=null) {
	if (isset($_SESSION['lankesi']) && $nick != $_SESSION['username']) {
		return (($data > $_SESSION['lankesi'])?'<img src="images/icons/new.png" onload="new Effect.Pulsate(this)" alt="Naujas" border="0" style="vertical-align: middle;" />':'');
	}
	else { return ''; }
}

//Pries kiek laiko
function kada($ts) {
	if ($ts == '' || $ts == "0000-00-00 00:00:00") { return ''; }
	$mins = floor((strtotime(date("Y-m-d H:i:s")) - strtotime($ts)) / 60);
	$hours = floor($mins / 60);
	$mins -= $hours * 60;
	$days = floor($hours / 24);
	$hours -= $days * 24;
	$weeks = floor($days / 7);
	$days -= $weeks * 7;
	$month = floor($weeks / 4);
	$days -= $month * 4;
	$year = floor($month  / 12);
	$days -= $year * 12;
	if ($year)
	return "prieš ".$year ." ". ($year > 1 ? "m." : "m.");
	if ($month)
	return "prieš ".$month ." ". ($month > 1 ? "mėn." : "mėn.");
	if ($weeks)
	return "prieš ".$weeks ." ". ($weeks > 1 ? "sav." : "sav.");
	if ($days)
	return "prieš ".$days ." ". ($days > 1 ? "d." : "d.");
	if ($hours)
	return "prieš ".$hours ." ". ($hours > 1 ? "val." : "val.");
	if ($mins)
	return "prieš ".$mins ." ". ($mins > 1 ? "min." : "min.");
	return "prieš < 1 minutę";
}

//vercia baitus i zmoniu kalba
function baitai($size,$digits=2,$dir=false) {
	$kb=1024; $mb=1024*$kb; $gb=1024*$mb; $tb=1024*$gb;
	if (($size==0)&&($dir)) { return " Nulis"; }
	elseif ($size<$kb) { return $size." Baitai"; }
	elseif ($size<$mb) { return round($size/$kb,$digits)." Kb"; }
	elseif ($size<$gb) { return round($size/$mb,$digits)." Mb"; }
	elseif ($size<$tb) { return round($size/$gb,$digits)." Gb"; }
	else { return round($size/$tb,$digits)." Tb"; }
}

// Trim a line of text to a preferred length
function trimlink($text, $length) {
	$dec = array("\"", "'", "\\", '\"', "\'", "<", ">");
	$enc = array("&quot;", "&#39;", "&#92;", "&quot;", "&#39;", "&lt;", "&gt;");
	$text = str_replace($enc, $dec, $text);
	if (strlen($text) > $length) $text = substr($text, 0, ($length-3))."...";
	$text = str_replace($dec, $enc, $text);
	return $text;
}

//Paskaiciuojam procentus
function procentai($reikia,$yra,$zenklas=false) {
	$return = (int)round((100 * $yra) / $reikia);
	if ($return > 100 && $zenklas) {
		$return = "<img src='images/icons/accept.png' class='middle' alt='100%' title='100%' borders='0' />";
	}
	elseif ($return > 0 && $zenklas) {
		$return = "<img src='images/icons/cross.png' class='middle' alt='".$return."%' title='".$reikia."/".$yra." - ".$return."%' borders='0' />";
	}
	return $return;
}

//Insert SQL - supaprastina duomenu iterpima, paduodam lentles pavadinima ir kitu argumentu asociatyvu masyva
function insert($table,$array) {
	return 'INSERT INTO `'.$table.'` ('.implode(', ',array_keys($array)).') VALUES ('.implode(', ',array_map('escape',$array)).')';
}

//echo "<img src='".pic('http://img95.imageshack.us/img95/6290/web1160860226jy1.jpg')."'>";
function pic($off_site,$size=150,$url='images/nuorodu/',$sub='url') {
	$pic_name = md5($off_site);
	$pic_name = $url.$sub."_".$pic_name.".jpg";
	if (!file_exists($pic_name) || (time() - filemtime($pic_name)) > 32400) { //9 valandos senumo
		clearstatcache();
		@unlink($pic_name);
		if (pic1($off_site,$size,$url,$sub)) {
			return $pic_name;
		}
		else { clearstatcache(); return $url."noimage.jpg"; }
	}
	else {
		clearstatcache(); return $pic_name;
	}
}

function pic1($off_site,$size=150,$url='images/nuorodu/',$sub='url') {
	$fp = @fopen($off_site, 'rb'); $buf = '';


	if ($fp) {
		stream_set_blocking($fp, TRUE);
		stream_set_timeout($fp,2);
		while (!feof ($fp)) {
			$buf .= fgets($fp, 4096);
		}

		$data = $buf;

		//set new height
		$src = @imagecreatefromstring ($data);
		if (empty($src)) { return false; }
		$width = @imagesx($src);
		$height = @imagesy($src);
		$aspect_ratio = $width/$height;

		//start resizing
		if ($width <= $size) {
			$new_w = $width;
			$new_h = $height;
		} else {
			$new_w = $size;
			$new_h = @abs($new_w/$aspect_ratio);
		}

		$img = @imagecreatetruecolor ($new_w,$new_h);

		//output image
		@imagecopyresampled ($img,$src,0,0,0,0,$new_w,$new_h,$width,$height);


		$file = $url.$sub."_".md5($off_site).".jpg";

		// determine image type and send it to the browser
		@imagejpeg($img, $file, 90);
		@imagedestroy($img);
		unset($buf);
		sleep(2);
	}
}

/**
 * Sulietuvinimas mėnesio
 * echo menesis(12); //Gruodis
 *
 * @param INT $men
 * @return string
 */
function menesis($men) {
	if (isNum($men)) { $ieskom = array(12,01,02,03,04,05,06,07,08,09,10,11); }
	else { $ieskom = array("December","January","February","March","April","May","June","July","August","September","October","November"); }
	$keiciam = array("Gruodis","Sausis","Vasaris","Kovas","Balandis","Gegužė","Birželis","Liepa","Rugpjūtis","Rugsėjis","Spalis","Lapkritis");
	return str_replace($ieskom,$keiciam,$men);
}

// grazina failus is nurodytos direktorijos ir sukisa i masyva
function getFiles($path,$denny='.htaccess|index.php|index.html|index.htm|index.php3|conf.php') {
	$denny = explode('|',$denny);
	$path = urldecode($path);
   $files = array();
   $fileNames = array();
   $i = 0;
   if (is_dir($path) && !in_array(basename($path), $denny)) {
       if ($dh = opendir($path)) {
           while (($file = readdir($dh)) !== false) {
               if (($file == ".") || ($file == "..")) continue;
               $fullpath = $path . "/" . $file;
               //$fkey = strtolower($file);
               $fkey = $file;
               while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
               $a = stat($fullpath);
               $files[$fkey]['size'] = $a['size'];
               if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if ($a['size'] > 1024 && $a['size'] <= 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K"; //patvarkom failo dydziu atvaizdavima
               else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
               else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
               $files[$fkey]['name'] = $file;
               $e = strip_ext($file); // $e failo pletinys - pvz: .gif
               $files[$fkey]['type'] = filetype($fullpath); // failo tipas, dir, file ir pan
               $k=$e.$file; // kad butu lengvau rusiuoti;
               $fileNames[$i++] = $k;
           }
           closedir($dh);
       }
		else die (klaida("KLAIDA","Negalime nuskaityti direktorijos:  $path"));
   }
   else die (klaida("KLAIDA","Tai ne direktorija:  $path"));
   sort($fileNames,SORT_STRING); // surusiuojam
   $sortedFiles = array();
   $i = 0;
   foreach($fileNames as $f) {
           $f = substr($f, 4, strlen($f)-4); //sutvarko failo pletinius
           if($files[$f]['name'] !='') $sortedFiles[$i++] = $files[$f];   
    }
   return $sortedFiles;
}

//Grazina direktoriju sarasa
function getDirs($dir) {
	if ($handle = opendir($dir)) {
		while (false !== ($file = readdir($handle))) {
			 if ($file != "." && $file != ".." && $file != ".svn" && is_dir($dir.$file)) {
				  $return[$file] = $file;
			 }
		}
		closedir($handle);
	}
	return $return;
}

// grazina failo pletini
function strip_ext($name,$ext='') {
	$ext = substr($name, strlen($ext)-4, 4);
	if(strpos($ext,'.') === false) { // jeigu tai folderis
		return "    "; // grazinam biski tarpu kad rusiavimas butu ciki, susirusiuoja - folderiai virsuje
	}
	return $ext; // jei tai failas grazinam jo pletini
}

function admin_login() {
	global $_SERVER,$admin_name,$admin_pass;
	if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != $admin_name || $_SERVER['PHP_AUTH_PW'] != $admin_pass) {
		header("WWW-Authenticate: Basic realm='AdminAccess'");
		header("HTTP/1.0 401 Unauthorized");
		header("status: 401 Unauthorized");
		mysql_query1("INSERT INTO `".LENTELES_PRIESAGA."logai` (`action` ,`time` ,`ip`) VALUES (".escape("ADMIN pultas - Klaida loginantis: User: ".(isset($_SERVER['PHP_AUTH_USER'])?$_SERVER['PHP_AUTH_USER']:"N/A")." Pass: ".(isset($_SERVER['PHP_AUTH_PW'])?$_SERVER['PHP_AUTH_PW']:"N/A")).",NOW(),INET_ATON(".escape($_SERVER['REMOTE_ADDR'])."));");
		die(klaida("Admin priėjimas uždraustas","Jūs mėginate patekti į tik administratoriams skirtą vietą. Betkokie mėginimai atspėti slaptažodį yra registruojami. <br/>p.s. Nekenčiu bomžų ir tai faktas"));
	}
	else {
		unset($admin_name,$admin_pass);
		return true;
	}
}

function get_user_os() {
  global $global_info, $HTTP_USER_AGENT, $HTTP_SERVER_VARS;
  if (!empty($global_info['user_os'])) {
    return $global_info['user_os'];
  }
  if (!empty($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) {
    $HTTP_USER_AGENT = $HTTP_SERVER_VARS['HTTP_USER_AGENT'];
  }
  elseif (getenv("HTTP_USER_AGENT")) {
    $HTTP_USER_AGENT = getenv("HTTP_USER_AGENT");
  }
  elseif (empty($HTTP_USER_AGENT)) {
    $HTTP_USER_AGENT = "";
  }
  if (eregi("Win", $HTTP_USER_AGENT)) {
    $global_info['user_os'] = "WIN";
  }
  elseif (eregi("Mac", $HTTP_USER_AGENT)) {
    $global_info['user_os'] = "MAC";
  }
  elseif (eregi("UNIX", $HTTP_USER_AGENT)) {
    $global_info['user_os'] = "Linux";
  }
  else {
    $global_info['user_os'] = "OTHER";
  }
  return $global_info['user_os'];
} 
function get_browser_info() {
  global $global_info, $HTTP_USER_AGENT, $HTTP_SERVER_VARS;
  if (!empty($global_info['browser_agent'])) {
    return $global_info['browser_agent'];
  }
  if (!empty($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) {
    $HTTP_USER_AGENT = $HTTP_SERVER_VARS['HTTP_USER_AGENT'];
  }
  elseif (getenv("HTTP_USER_AGENT")) {
    $HTTP_USER_AGENT = getenv("HTTP_USER_AGENT");
  }
  elseif (empty($HTTP_USER_AGENT)) {
    $HTTP_USER_AGENT = "";
  }
  if (eregi("MSIE ([0-9].[0-9]{1,2})", $HTTP_USER_AGENT, $regs)) {
    $global_info['browser_agent'] = "MSIE";
    $global_info['browser_version'] = $regs[1];
  }
  elseif (eregi("Mozilla/([0-9].[0-9]{1,2})", $HTTP_USER_AGENT, $regs)) {
    $global_info['browser_agent'] = "MOZILLA";
    $global_info['browser_version'] = $regs[1];
  }
  elseif (eregi("Opera(/| )([0-9].[0-9]{1,2})", $HTTP_USER_AGENT, $regs)) {
    $global_info['browser_agent'] = "OPERA";
    $global_info['browser_version'] = $regs[2];
  }
  else {
    $global_info['browser_agent'] = "OTHER";
    $global_info['browser_version'] = 0;
  }
  return $global_info['browser_agent'];
} 

?>
